<?php

namespace app\wechat\controller;

use app\common\model\UserInfoModel;

/**
 * Class Climbtree
 * @package app\wechat\controller
 */
class Climbtree extends \think\Controller
{

    /**
     * 修改摇一摇次数
     *
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function update()
    {
        $barragerModel = new UserInfoModel();
        $arr = $this->ioAll();
        $userInfo = $barragerModel->get(['openId' => $arr['openId']]);
        if ($userInfo['times'] + 10 == $arr['times']) {
            $arr['gameTime'] = time();
            $userSave = $barragerModel->updateEx($arr);
        } else {
            $userSave = false;
        }
        return $userSave ? $this->ok($userSave) : $this->fail("摇一摇失败");
    }


    public function list($limit = 10)
    {
        $barragerModel = new UserInfoModel();
        $items = $barragerModel->where('times <> 0')->order('times desc,gameTime asc')->limit($limit)->select();
        foreach ($items as $index => $item) {
            $item['nickName'] = self::match_chinese(self::filterEmoji(self::reeChar($item['nickName'])));
            $items[$index] = $item;
        }
        return $items ? $this->ok($items, $barragerModel->count()) : $this->fail("没有数据");
    }

    // 过滤特殊字符 删除空格与回车,去除特殊字符
    function reeChar($strParam)
    {
        $regex = "/\/|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
        $qian = array(" ", "　", "\t", "\n", "\r");
        $cv = preg_replace($regex, "", $strParam);
        return str_replace($qian, '', $cv);
    }

    // 保留中文
    function match_chinese($chars, $encoding = 'utf8')
    {
        $pattern = ($encoding == 'utf8') ? '/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u' : '/[\x80-\xFF]/';
        preg_match_all($pattern, $chars, $result);
        $temp = join('', $result[0]);
        return $temp;
    }

    // 过滤掉emoji表情
    function filterEmoji($str)
    {
        $str = preg_replace_callback('/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }
}
